package com.ijustyce.fastandroiddev.net;

import com.ijustyce.fastandroiddev.unit.LogCat;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;

/**
 * Created by yc on 2015/8/14.
 */
public class HttpResponse {

    private static final String SUCCESS = "100";
    private HttpInterface httpInterface;
    public HttpResponse(HttpInterface httpInterface){
        this.httpInterface = httpInterface;
    }
    public AsyncHttpResponseHandler listener = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            parseSuccess(response);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            throwable.printStackTrace();
            httpInterface.fail("");
        }
    };

    private void parseSuccess(JSONObject json){

        LogCat.i("json is " + json);
        if (httpInterface==null){
            LogCat.e("httpInterface is null return ");
        }
        if (!json.has("result")){
            LogCat.e("error", "no result");
            return;
        }
        try {
            JSONObject result = json.getJSONObject("result");
            if (result.has("code")){
                String code = result.getString("code");
                if (!SUCCESS.equals(code)){
                    String msg = result.getString("msg");
                    if(msg != null){
                        httpInterface.fail(msg);
                    }
                }else{
                    if (json.has("data")){
                        if (json.isNull("data")){
                            httpInterface.success(result);
                            return;
                        }
                        JSONObject data = json.getJSONObject("data");
                        httpInterface.success(data);
                    }
                }
            }
        }catch (JSONException e){
            httpInterface.fail(e.getLocalizedMessage());
            LogCat.e("HttpResponse", "HttpResponse error " + e.getMessage());
        }
    }
}
